<template>
    <div class="app-container">
        <el-form :model="searchForm" inline ref="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="工号：" prop="employeeNo">
                        <el-input clearable v-model="searchForm.employeeNo" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名：" prop="name">
                        <el-input clearable v-model="searchForm.name" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="部门：" prop="department">
                        <el-cascader clearable :options="departmentOpt" :props="optionProps" v-model="searchForm.department" change-on-select></el-cascader>
                    </el-form-item>
                    <el-form-item label="职位：" prop="post">
                        <el-select v-model="searchForm.post" clearable placeholder="请选择">
                            <el-option v-for="item in positionOpt" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" @click="init('search')" >查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick" type="primary" style="position: absolute;right: 0;">添加员工</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin-bottom: 20px;">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="employeeNo" label="工号" align="center"></el-table-column>
            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="orgDepartmentName" :formatter="orgDepartmentNameFun" label="部门" align="center"></el-table-column>
            <el-table-column prop="orgPositionName" label="职位" align="center"></el-table-column>
            <el-table-column prop="officePhone" label="办公电话" align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
            <el-table-column prop="locked" :formatter="lockedFun" label="锁定状态" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" align="center"></el-table-column>
            <el-table-column label="操作" width="240" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" type="primary" plain size="mini">编辑</el-button>
                    <el-button @click.stop="lockClick(scope.row)" type="warning" plain size="mini">{{(scope.row.locked == 0) ? '解锁' : '锁定'}}</el-button>
                    <el-button @click.stop="resetClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :title="nowTit" :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="手机号：" prop="userPhone" v-show="popStatus == 0">
                    <el-row>
                        <el-col :span="12"><el-input v-model="userPhone" placeholder="请输入"></el-input></el-col>
                        <el-col :span="12"><el-button type="primary" @click="userList" style="display: inline-block;margin-left: 10px;">查询</el-button></el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="用户：" prop="sysUserId">
                    <el-select v-model="dataForm.sysUserId" placeholder="必填项。查询手机号获取用户信息" style="display: inline-block;width: 100%;" disabled>
                        <el-option v-for="item in userOpt" :key="item.id" :label="item.nickName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工号：" prop="employeeNo">
                    <el-input v-model="dataForm.employeeNo" placeholder="必填项。请输入工号，如JA000001"></el-input>
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="dataForm.name" placeholder="必填项。请输入真实姓名，如张思思"></el-input>
                </el-form-item>
                <el-form-item label="部门：" prop="orgDepartmentId">
                    <el-cascader :options="departmentOpt" :props="optionProps" v-model="orgDepartmentId" change-on-select placeholder="必填项。请选择部门" style="width: 100%;"></el-cascader>
                </el-form-item>
                <el-form-item label="职位：" prop="orgPositionId">
                    <el-select v-model="dataForm.orgPositionId" placeholder="必填项。请选择职位" style="display: inline-block;width: 100%;">
                        <el-option v-for="item in positionOpt" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="办公电话：" prop="officePhone">
                    <el-input v-model="dataForm.officePhone" maxlength="11" placeholder="请输入办公电话，如18899996666，02988889999，029-8889999"></el-input>
                </el-form-item>
                <el-form-item label="办公邮箱：" prop="email">
                    <el-input v-model="dataForm.email" placeholder="请输入办公邮箱，如12264104@qq.com"></el-input>
                </el-form-item>
                <el-form-item label="锁定状态：" prop="locked">
                    <el-select v-model="dataForm.locked" placeholder="请选择" style="display: inline-block;width: 100%;">
                        <el-option v-for="item in lockedOpt" :key="item.key" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="saveClick('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { findDepartment } from '@/api/organization/department'
import { findPosition } from '@/api/organization/position'
import { findSysUserPageRecord } from '@/api/user-management/sys-user'
import { addEmployee, findEmployee, detailEmployee, editEmployee, lockedEmployee, delEmployee } from '@/api/organization/employees'
import { getCookie, setCookie } from '@/utils/auth'
import { validEmail, isvalidPhone, isvalidTel } from '@/utils/validate'
export default {
    name: 'Employee',
    data() {
        var isEmail = (rule, value, callback) => {
            if( value && !validEmail(value) ){
                return callback(new Error('请输入正确的邮箱格式！'));
            }else{
                return callback();
            }
        };
        var validPhone=(rule, value,callback)=>{
            if (!value){
                callback(new Error('请输入手机号或电话号'))
            }else{
                if(isvalidPhone(value) || isvalidTel(value)){
                    callback()
                }else{
                    callback(new Error('请输入正确的手机号或电话号'))
                }
            }
        }
        return{
            searchForm: {
                employeeNo: '',
                name: '',
                department: [],
                post: '',
            },
            tableData: [],
            nowTit: '',
            showDialog: false,
            dataForm: {
                employeeNo: '',
                orgDepartmentId: '',
                email: '',
                locked: '1',
                name: '',
                officePhone: '',
                orgPositionId: '',
                sysUserId: ''
            },
            rules: {
                employeeNo: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
                sysUserId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
                email: [
                    { validator: isEmail, trigger: 'blur' }
                ],
                officePhone: [
                    {  message: '请输入手机号码', trigger: 'blur' },
                    {  trigger: 'blur', validator: validPhone }
                ],
                orgPositionId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
            },
            lockedOpt: [
                {label: '锁定', value: 0},
                {label: '正常', value: 1}
            ],
            pageData: {},
            nowId: '',
            departmentOpt: [],
            positionOpt: [],
            userOpt: [],
            nowPage: 0,
            pageSize: 10,
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            orgDepartmentId: [],
            userPhone: '',
            popStatus: 0,
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            //获取列表信息
            //筛选条件
            let employeeNo, name, department, post;
            employeeNo = _this.searchForm.employeeNo;
            name = _this.searchForm.name;
            if(_this.searchForm.department.length > 0){
                department = _this.searchForm.department[_this.searchForm.department.length - 1];
            }else{
                department = ''
            }
            post = _this.searchForm.post;
            findEmployee( _this.nowPage, _this.pageSize, employeeNo, name, department, post ).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object;
                    _this.tableData = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        departmentList(){
            const _this = this;
            findDepartment( 0, 10000 ).then(response => {
                if(response.code == 200){
                    _this.departmentOpt = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if((data[i].children == null) || (data[i].children.length<1)){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        positionList(){
            const _this = this;
            findPosition( 0, 10000 ).then(response => {
                if(response.code == 200){
                    _this.positionOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取用户信息
        userList(){
            const _this = this;
            if(_this.userPhone === ''){
                this.$message.warning('请输入需要查询的手机号');
                return
            }
            findSysUserPageRecord(0, 10000,_this.userPhone,'').then(response => {
                if(response.code == 200){
                    _this.userOpt = response.object.content;
                    _this.dataForm.sysUserId = response.object.content[0].id;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.userPhone = '';
            this.dataForm.employeeNo = '';
            this.dataForm.orgDepartmentId = '';
            this.orgDepartmentId = [];
            this.dataForm.email = '';
            this.dataForm.locked = 1;
            this.dataForm.name = '';
            this.dataForm.sysUserId = '';
            this.dataForm.officePhone = '';
            this.dataForm.orgPositionId = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //删
        resetClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.name+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delEmployee(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.dataForm.orgDepartmentId = row.orgDepartmentId;
            this.orgDepartmentId
            //处理所属部门id
            if(row.orgDepartmentEntityList){
                let arr = [];
                for (const key in row.orgDepartmentEntityList) {
                    if (row.orgDepartmentEntityList.hasOwnProperty(key)) {
                        const element = row.orgDepartmentEntityList[key];
                        arr.push(element.id);
                    }
                }
                this.orgDepartmentId = arr;
            }
            this.dataForm.employeeNo = row.employeeNo;
            this.dataForm.email = row.email;
            this.dataForm.locked = row.locked;
            this.dataForm.sysUserId = row.sysUserId;
            this.dataForm.name = row.name;
            this.dataForm.officePhone = row.officePhone;
            this.dataForm.orgPositionId = row.orgPositionId;
            this.showDialog = true;
        },
        //锁/解
        lockClick(row){
            let usingStatus,isUsing;
            if(row.locked == 1){  //启用状态
                usingStatus = 0;
                isUsing = '锁定';
            }else{
                usingStatus = 1;
                isUsing = '解锁';
            }

            let _this = this;
            this.$confirm('确定 '+ isUsing + row.name +' 的员工信息吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //启用禁用
                lockedEmployee(row.id, getCookie('pid'), usingStatus ).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //保存
        saveClick(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(_this.orgDepartmentId.length > 0){
                        _this.dataForm.orgDepartmentId = _this.orgDepartmentId[_this.orgDepartmentId.length - 1];
                    }else{
                        this.$message.warning('请选择部门');
                        return
                    }
                    //提交
                    if(_this.popStatus == 0){  //添加
                        addEmployee(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editEmployee(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.$refs[formName].resetFields();
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        lockedFun(row){
            if(row.locked == 0){
                return '锁定'
            }else if(row.locked == 1){
                return '正常'
            }
        },
        orgDepartmentNameFun(row){
            //处理所属部门name
            if(row.orgDepartmentEntityList){
                let arr = '';
                for (const key in row.orgDepartmentEntityList) {
                    if (row.orgDepartmentEntityList.hasOwnProperty(key)) {
                        const element = row.orgDepartmentEntityList[key];
                        arr += element.name + ' / '
                    }
                }
                return arr.substr(0,arr.length - 3)
            }
        },
    },
    mounted(){
        this.init();
        this.departmentList();
        this.positionList();
    }
}
</script>
